package main

import (
	"MqttCloudProtocolServer/publiclib/define"
	"MqttCloudProtocolServer/publiclib/logiclib"
	"flag"
	"fmt"
	"time"

	"github.com/wonderivan/logger"

	//"log"
	"os"
	"path/filepath"
	"strings"
)

func linuxInit() {
	// change to current dir
	if path, err := os.Executable(); err != nil {
		logger.Fatal(err)
	} else {
		logger.Info(path)
		appPath := filepath.Dir(path)
		logger.Info(appPath)
		if err := os.Chdir(appPath); err != nil {
			logger.Fatal(err)
		}
		define.InitInternalPath()
		define.CheckIsLog("protocol.log")
		isrunning = true
	}
}

//StartServer 启动服务
func StartServerLinux() {
	if cloudServerContent == nil {
		GetMainClass()
	}
	cloudServerContent.Start()
	//go getCMD("ProtocolServer")
	cloudServerContent.Wait()
	isrunning = false
}

func getCMDLinux(name string) {
	client := new(logiclib.RPCClientManager)
	client.Init()
	client.Start()
	for isrunning {
		cmd := client.GetCommand(&name)
		if cmd != nil {
			if cmd.Name == name {
				switch strings.ToUpper(cmd.Command) {
				case "STOP":
					StopServerLinux()
					break
				}
			}
		}
		time.Sleep(time.Millisecond * 100)
	}
}

//StopServer 停止服务
func StopServerLinux() {
	cloudServerContent.Stop(true)
}

func mainlinux() {
	flag.Parse()
	// run as normal
	if *flagChildProcess {
		logger.Info("CHILD MODE")
		go getCMDLinux("ProtocolServer")
	} else {
		var cmdLine string
		consoleCmd := func() {
			for isrunning && strings.ToUpper(cmdLine) != "EXIT" {
				fmt.Scanln(&cmdLine)
				time.Sleep(time.Second)
			}
			StopServerLinux()
		}
		go consoleCmd()
	}
	StartServerLinux()
}
